import { ref } from 'vue';
import type { SaveRecordParams } from '@/api/chat/types';
import { reportChatService } from '@/services/reportChatService';
import { useDebounce } from '@/utils/utils';

interface StreamOptions {
  url?: string;
  method?: string;
  headers?: Record<string, any>;
  body?: Record<string, any>;
  timeout?: number;
  thinkingFlag?: string;
  answeringFlag?: string;
  useStartTag?: boolean;
  onThinking?: (content: string) => void;
  onAnswerStart?: () => void;
  onAnswering?: (content: string) => void;
  onData?: (data: string) => void;
  onComplete?: () => void;
  onError?: (error: any) => void;
}

export const useFetchStream = (options: StreamOptions = {}) => {
  // 配置参数解析
  const {
    url = '/intelligent', // 接口地址
    method = 'POST',
    headers = {},
    body = {},
    timeout = 10 * 60 * 1000, // 超时时间(10分钟)
    thinkingFlag = '<think>',
    answeringFlag = '</think>',
    useStartTag = false,
    onThinking = () => ({}),
    onAnswerStart = () => ({}),
    onAnswering = () => ({}),
    onData = () => ({}),
    onComplete = () => ({}),
    onError = () => ({})
  } = options;

  // 核心状态管理
  const isThinking = ref(false);
  const isAnswering = ref(false);
  const isLoading = ref(false);
  const error = ref<any>(null);
  const controller = ref(new AbortController());
  const timeoutId = ref<any>(null);
  const thinkStartTime = ref(0);
  const thinkTime = ref<any>(0);
  const thinkingBuffer = ref('');
  const answeringBuffer = ref('');
  const conversationId = ref<number | null>(null);

  // 状态初始化函数
  const init = () => {
    isThinking.value = false;
    isAnswering.value = false;
    isLoading.value = false;
    thinkStartTime.value = 0;
    thinkTime.value = 0;
    thinkingBuffer.value = '';
    answeringBuffer.value = '';
  };

  // 防抖请求函数（600ms防抖间隔）
  const fetchData = useDebounce(async (requestBody: any = {}) => {
    try {
      // 会话开始时，创建会话记录
      const recordData: SaveRecordParams = {
        agent: requestBody.name || requestBody.agent || '智能助手',
        files: requestBody.files && requestBody.files.length > 0 ? JSON.stringify(requestBody.files) : '',
        content: requestBody.queryStr || requestBody.query || requestBody.content || ''
      };

      const sessionResult = await reportChatService.saveConversationRecord(recordData);
      if (!sessionResult) {
        throw new Error('创建会话失败！请重试');
      }

      conversationId.value = sessionResult.sesssionId;
      reportChatService.setConversationId(sessionResult.sesssionId);
      
      onAnswerStart && onAnswerStart();
      
      thinkingBuffer.value = '';
      answeringBuffer.value = '';
      isLoading.value = true;
      error.value = null;
      controller.value = new AbortController();

      // 超时处理逻辑
      if (timeout) {
        timeoutId.value = setTimeout(() => {
          controller.value.abort();
          error.value = new Error('请求超时');
          onError(error.value);
        }, timeout);
      }

      // 发起fetch请求
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify({ ...body, ...requestBody }),
        signal: controller.value.signal
      });

      // 处理非200响应
      if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`);
      }

      // 流式数据解析
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let isFirstChunk = true;
      thinkStartTime.value = Date.now();

      // 流数据处理循环
      while (true) {
        const { done, value } = await reader!.read();
        
        if (done) {
          // 会话结束时，保存会话记录
          await reportChatService.saveConversationRecord({
            agent: requestBody.name || requestBody.agent || '智能助手',
            parentId: sessionResult.messageId,
            role: requestBody.name || requestBody.agent || '智能助手',
            sesssionId: sessionResult.sesssionId,
            content: answeringBuffer.value,
            thinkingContent: thinkingBuffer.value,
            thinkingEnabled: requestBody.isDeepThinking ? 1 : 0
          });
          break;
        }

        // 解码并拼接数据块
        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;

        if (buffer.includes(thinkingFlag) && buffer.includes(answeringFlag)) {
          if (isFirstChunk) {
            thinkTime.value = ((Date.now() - thinkStartTime.value) / 1000).toFixed(0);
            isFirstChunk = false;
          }
          
          isThinking.value = false;
          isAnswering.value = true;
          
          const answerStart = buffer.indexOf(answeringFlag) + answeringFlag.length;
          answeringBuffer.value = buffer.slice(answerStart);
          thinkingBuffer.value = buffer.slice(
            buffer.indexOf(thinkingFlag) + thinkingFlag.length,
            buffer.indexOf(answeringFlag)
          );
          
          onAnswering(answeringBuffer.value);
        } else if (buffer.includes(thinkingFlag) && !buffer.includes(answeringFlag)) {
          isThinking.value = true;
          thinkingBuffer.value = buffer.slice(buffer.indexOf(thinkingFlag) + thinkingFlag.length);
          onThinking(thinkingBuffer.value);
        } else if (!buffer.includes(thinkingFlag)) {
          if (isFirstChunk) {
            thinkTime.value = ((Date.now() - thinkStartTime.value) / 1000).toFixed(0);
            isFirstChunk = false;
          }
          
          isAnswering.value = true;
          answeringBuffer.value = buffer;
          onAnswering(answeringBuffer.value);
        }

        onData(buffer);
      }

      onComplete();
    } catch (err: any) {
      // 异常处理（排除主动取消请求）
      if (err.name !== 'AbortError') {
        error.value = err;
        onError(err);
      }
    } finally {
      // 清理操作
      clearTimeout(timeoutId.value);
      isLoading.value = false;
    }
  }, 600, { leading: true, trailing: false });

  // 请求中止函数
  const abort = () => {
    controller.value.abort();
    isThinking.value = false;
    isAnswering.value = false;
    isLoading.value = false;
    error.value = new Error('请求已取消');
    onError(error.value);
  };

  return {
    isThinking,
    isAnswering,
    isLoading,
    thinkTime,
    error,
    thinkingBuffer,
    answeringBuffer,
    conversationId,
    fetchData,
    init,
    abort
  };
};
